import { create } from 'zustand'
import { UserService } from '../services/user'

interface UserInfo {
  phone: string
  token: string
  lastLoginTime: number
  [key: string]: any // 支持任意字符串键值对
}

interface UserState {
  userInfo: UserInfo | null
  loading: boolean
  maskedPhone: string
  isLoggedIn: boolean
  token: string
  phone: string
  init: () => Promise<void>
  saveUserInfo: (info: UserInfo) => Promise<void>
  login: (phone: string, code: string) => Promise<void>
  logout: () => Promise<void>
  loginWithToken: (token: string) => Promise<boolean>
}

export const useUserStore = create<UserState>((set, get) => ({
  userInfo: null,
  loading: false,
  maskedPhone: '',
  isLoggedIn: false,
  token: '',
  phone: '',

  // 从 storage 初始化用户信息
  init: async () => {
    try {
      const result = await chrome.storage.local.get('userInfo')
      if (result.userInfo) {
        const userInfo = result.userInfo
        // 验证 token 是否过期（这里设置 30 天过期）
        const now = Date.now()
        const lastLoginTime = userInfo.lastLoginTime
        if (now - lastLoginTime > 30 * 24 * 60 * 60 * 1000) {
          // token 过期，清除用户信息
          await get().logout()
          return
        }
        
        // 更新所有相关状态
        const phone = userInfo.phone
        const maskedPhone = phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
        set({ 
          userInfo,
          maskedPhone,
          isLoggedIn: !!userInfo.token,
          token: userInfo.token || '',
          phone: phone || ''
        })
      }
    } catch (error) {
      console.error('Failed to init user info:', error)
    }
  },

  // 保存用户信息到 storage
  saveUserInfo: async (info: UserInfo) => {
    try {
      await chrome.storage.local.set({ userInfo: info })
      const phone = info.phone
      const maskedPhone = phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      set({ 
        userInfo: info,
        maskedPhone,
        isLoggedIn: !!info.token,
        token: info.token || '',
        phone: phone || ''
      })
    } catch (error) {
      console.error('Failed to save user info:', error)
      throw error
    }
  },

  // 登录
  login: async (phone: string, code: string) => {
    set({ loading: true })
    try {
      // 调用 service 进行登录
      const result = await UserService.loginWithCode(phone, code)
      console.log('登录结果:', result)
      
      // 保存用户信息
      const userInfo: UserInfo = {
        phone,
        token: result.token || result.accessToken || '', // 兼容不同的 token 字段名
        lastLoginTime: Date.now(),
        ...result // 展开其他可能的字段
      }
      await get().saveUserInfo(userInfo)
    } finally {
      set({ loading: false })
    }
  },
  loginWithToken: async (token: string) => {
    set({ loading: true })
    try {
      const result = await UserService.loginWithToken(token)
      if (result === null) {
        return false
      }
      // 保存用户信息
      const userInfo: UserInfo = {
        userInfo: result,
        phone: "",
        token: token, // 兼容不同的 token 字段名
        lastLoginTime: Date.now(),
         // 展开其他可能的字段
      }
      await get().saveUserInfo(userInfo)
      return true
    } finally {
      set({ loading: false })
    }
  },
  // 登出
  logout: async () => {
    try {
      await chrome.storage.local.remove('userInfo')
      set({ 
        userInfo: null,
        maskedPhone: '',
        isLoggedIn: false,
        token: '',
        phone: ''
      })
    } catch (error) {
      console.error('Failed to logout:', error)
      throw error
    }
  }
})) 